import { useEffect, useState, useRef } from "react";
import { Text, View, Image, Input } from "@tarojs/components";
import { Button, DatePicker, Dialog, Overlay, Picker, Popup, Tag } from "@nutui/nutui-react-taro";
import InfiniteLoading from "../../components/InfiniteLoading";
import InfiniteLoadingFoot from "../../components/InfiniteLoadingFoot";
import usePage from "../../hooks/usePage";
import { iconAdd, iconClear, iconDownGray, iconClockBlack } from "../../assets/files";
import { baseUrl, uploadFile, uploadFileList } from "../../utils/request.js";
import dayjs from "dayjs";

import Taro, { useDidShow } from "@tarojs/taro";
import { complete, trainingInfoList, update } from "../../api/apply.js";
import { navigateTo } from "../../common/_";
import { getStore } from "../../utils/localStore.js";
import { getSystemDictValue } from "../../utils/globalData.js";
import PageList from "../../components/pageList/pageList.jsx";
import EditModal from "./components/edit-modal/index.jsx";
import "./index.scss";

definePageConfig({
  navigationBarTitleText: "测试记录",
  disableScroll: true,
});

export default function Record() {
  const pageListRef = useRef();

  const [recoverVisible, setRecoverVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [endVisible, setEndVisible] = useState(false);
  const [timeStartVisible, setTimeStartVisible] = useState(false);
  const [timeEndVisible, setTimeEndVisible] = useState(false);
  const [timeType, setTimeType] = useState();
  const [imgList, setImgList] = useState([]);
  const [timeList, setTimeList] = useState([])
  const [isVisible2, setIsVisible2] = useState(false)
  const [trainingTime, setTrainingTime] = useState("")
  const [leturer, setLeturer] = useState("")

  const [curData, setCurData] = useState({})

  const [params, setParams] = useState({
    startDate: dayjs().subtract(151, 'day').format('YYYY-MM-DD'),
    endDate: dayjs().add(31, 'day').startOf('day').format('YYYY-MM-DD'),
    userId: getStore("userInfo").id,
    pageSize: 10,
    auditState: "",
    customTime: new Date()
  });

  useEffect(() => {
    Taro.eventCenter.on('reAuditList', handleUpdate);

    return () => {
      Taro.eventCenter.off('reAuditList', handleUpdate);
    }
  }, [])

  const handleUpdate = () => {
    pageListRef.current?.refresh();
  }

  useEffect(() => {
    getGennerDate()
  }, [])
  // const { listData, refreshing, empty, loadMore, onPull, onLoad } = usePage({
  //   request: trainingInfoList,
  //   params,
  // });

  const [shenqStatus, setShenqStatus] = useState([
    {
      id: "",
      name: "全部",
      color: '#FF8916',
      bgColor: 'rgba(255, 212, 148, 0.3)'
    },
    {
      id: 1,
      name: "审核中",
      color: '#FF8916',
      bgColor: 'rgba(255, 212, 148, 0.3)'
    },
    {
      id: 2,
      name: "待培训",
      color: '#6486FF',
      bgColor: 'rgba(148, 197, 255, 0.5)'
    },
    {
      id: 3,
      name: "已拒绝",
      color: '#FF1616',
      bgColor: 'rgba(255, 148, 148, 0.5)'
    },
    {
      id: 4,
      name: "已培训",
      color: 'rgba(7, 193, 96, 1)',
      bgColor: 'rgba(176, 255, 214, 0.35)'
    },
  ]);

  const navigateToDetails = (item) => {
    navigateTo('/pages/apply-detail/index', {
      userExamId: item.id
    })
  };

  const getGennerDate = () => {
    const today = dayjs();
    let dates = [];
    for (let i = 1; i <= 30; i++) {
      const date = today.add(i + 1, 'day').format('MM-DD'); // i + 1 因为起始点是后两天
      dates.push({ text: date, value: date });
    }
    setTimeList([dates, [
      { text: "09:00", value: "09:00" },
      { text: "10:00", value: "10:00" },
      { text: "11:00", value: "11:00" },
      { text: "15:00", value: "15:00" },
      { text: "16:00", value: "16:00" },
      { text: "17:00", value: "17:00" }
    ]])
  }

  function selectTime(type) {
    setTimeType(type);
    if (type === "start") {
      setTimeStartVisible(true);
    } else {
      setTimeEndVisible(true);
    }
  }

  function confirmTime(values, options) {
    console.log(values, options);
    let data = ""
    if (values.join("-").includes("02-31") || values.join("-").includes("02-30")) {
      data = dayjs().year() + '-02-01'
    } else {
      data = values.join("-")
    }
    if (timeType === "start") {
      setParams({
        ...params,
        startDate: data
      })
    } else {
      setParams({
        ...params,
        endDate: data
      })
    }
  }


  const [visible, setVisible] = useState(false)
  const [baseDesc, setBaseDesc] = useState('')
  const listData1 = [
    [
      { value: "", text: '全部' },
      { value: 1, text: '审核中' },
      { value: 2, text: '待培训' },
      { value: 3, text: '已拒绝' },
      { value: 4, text: '已培训' },
    ],
  ]
  const changePicker = (list, option, columnIndex) => {
    console.log(columnIndex, option)
  }
  const confirmPicker = (
    options,
    values
  ) => {
    setParams({
      ...params,
      auditState: values[0] ? parseInt(values[0]) : ""
    })

  }

  const setVisibleFn = (e, item) => {
    e.stopPropagation()
    setCurData(item)
    setEditVisible(true)
  }

  const endPeixun = (e, item) => {
    e.stopPropagation()
    setCurData(item)
    setEndVisible(true)
  }

  const [moduleId] = useState("ci15Jz2DJ6ZNkLVVJCATmZv3YZO3yI0BJ4fDE0Gog-4")
  const toDetail = (e, item) => {
    e.stopPropagation()


    Taro.requestSubscribeMessage({
      tmplIds: [moduleId],
      success(res) {
        console.log(res);
        // console.log(res[moduleId]);
        if (res[moduleId] === 'reject') {
          // ioenset()
          // Taro.showModal({
          //   content:"消息通知已关闭，去打开？",
          //   complete(res){
          //     if(res.confirm){
          //       ioenset()
          //     }
          //   }
          // })
        }else{
          Taro.showToast({
            icon:'none',
            title:'消息通知已打开'
          })
        }
        // setCheckedAsync(true)
      },
      fail(err) {
        console.log(err);

      },
      complete(res){
        item.isAudit = true
        navigateTo('/pages/apply-detail/index', { id: item.id, isAudit: true })
      }
    })



   
  }

  const delImg = (index) => {
    let arr = JSON.stringify(imgList)
    arr = JSON.parse(arr)
    arr.splice(index, 1)
    setImgList(arr)
  }

  function selectImg() {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: async function (res) {
        // 选择成功时返回的临时文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  const tempFilePaths = res.tempFilePaths?.[0];
        // console.log(tempFilePaths1);

        const tempFilePaths = res.tempFilePaths?.[0];
        console.log(tempFilePaths); // 这里可以获取到图片的临时路径
        Taro.showLoading({
          title: "上传中...",
        });
        // const { data, success, msg } = await uploadFileList("xiaofangPeixun", tempFilePaths.toString());
        const { data, success, msg } = await uploadFile("xiaofangPeixun", tempFilePaths);
        setImgList([...imgList, data.fileUrl])
        // updateUser({ headId: data.fileUrl }).then(rs=>{
        //   getUserInfo()
        // })

        Taro.hideLoading();
        if (!success) {
          Taro.showToast({
            title: msg,
            icon: "none",
          });
          return;
        }

      }
    });
  }


  function matchType(type) {
    for (let index = 0; index < shenqStatus.length; index++) {
      const element = shenqStatus[index];
      if (element.id === type) {
        return element
      }

    }
  }

  const editList = async (name, id) => {

    // curData.leturer = id
    // curData.leturerName = name
    // console.log(curData);

    // return;
    curData.leturer = name
    const { msg, success } = await update(curData)
    if (success) {
      setEditVisible(false)
      Taro.showToast({
        title: '修改成功',
        icon: 'none'
      })
    } else {
      Taro.showModal({
        content: msg
      })
    }
  }

  const overSubmit = async () => {
    console.log(imgList);
    if (imgList.length === 0) {
      Taro.showToast({
        title: '请上传图片',
        icon: 'none'
      })
      return
    }

    if (imgList.length > 10) {
      Taro.showToast({
        title: '图片不能超过10张',
        icon: 'none'
      })
      return
    }
    let arr = []
    imgList.forEach(v => {
      arr.push({
        sysFileId: v,
        sysFileUrl: v,
        trainingInfoId: curData.id
      })
    })


    const { success, msg } = await complete({ id: curData.id, list: arr })
    if (success) {
      setEndVisible(false)
      Taro.showToast({
        title: '提交成功',
        icon: 'none'
      })
      setParams({
        ...params,
        customTime: new Date()
      })
    } else {
      Taro.showModal({
        content: msg
      })
    }
  }

  useEffect(() => {
    setImgList([])
  }, [endVisible])

  const clearTimeout = () => {
    setParams({
      ...params,
      startDate: "",
      endDate: "",
    })
  }

  const renderListItem = (item) => {
    return (
      <View
        className={"list-item"}
        onClick={(e) => toDetail(e, item)}
      >
        <View className="tie">
          <View className="iteWrap" style={{ flex: 1 }}>
            <Text className="ites">
              培训时间：{item.trainingTime?.substr(0, 16)}
            </Text>
            <Text className="reTypeText" style={{ color: matchType(item?.auditState).color, backgroundColor: matchType(item?.auditState).bgColor }}>
              {matchType(item?.auditState).name}
            </Text>
          </View>
          {/* <Text className="rightDes">
                  {item.startTime}
                </Text> */}
          {/* <Image className="rightIcon" src={iconRightGray} /> */}
        </View>
        <View className="content">
          <View className="gonggsiWrap">
            <Tag className="itemTag" background="#2A64F4" plain>{getSystemDictValue(77, item?.category)?.name}</Tag>
            <Text className="companyName" style={{ marginLeft: '2px' }}>{item.enterpriseName}</Text>
          </View>
          <View>
            <Text className="pNum">培训人数：{item.number}</Text>
            <Text className="pNum" style={{ marginLeft: 12 }}>辖区：{getSystemDictValue(13, item?.jurisdiction)?.name}</Text>
            {/* <Text className="pNum" style={{ marginLeft: 12 }}>单位类别：{getSystemDictValue(77, item?.category)?.name}</Text> */}
          </View>
        </View>
        <View className="btnWrap" style={{ justifyContent: item.auditState === 3 ? "flex-start" : "flex-end" }}>
          {
            item.auditState === 3 &&
            <Text>拒绝原因：{item.auditReason}</Text>
          }
          {
            item.auditState === 2 &&
            <>
              {/* <Button type="success" style={{ marginRight: '12px' }} onClick={(e) => {
                //  e.stopPropagation()
                // setRecoverVisible(true)
                setVisibleFn(e, item)
              }}> 编 辑 </Button> */}

              <Button onClick={(e) => endPeixun(e, item)} type="info" style={{}}>完成培训</Button>
            </>
          }
          {
            item.auditState === 1 && <Button onClick={(e) => toDetail(e, item)} type="info" style={{}}>审 核</Button>
          }
        </View>

      </View>
    )
  }

  const renderHeader = () => {
    return (
      <View className="topSelectWrap">
        <View className="timeWrap">
          <Image src={iconClockBlack} className="clockSty" />
          <Text className="timeText" onClick={() => selectTime("start")}>
            {params.startDate || '请选择'}
          </Text>
          <Text className="zhi">至</Text>
          <Text className="timeText" onClick={() => selectTime('end')}>{params.endDate || '请选择'}</Text>
          <Image onClick={() => clearTimeout()} src={iconClear} className="iconClose" />
        </View>
        <View className="shai" onClick={() => {
          setVisible(true)
        }}>
          <Text>{matchType(params.auditState).name}</Text>
          <Image src={iconDownGray} className="downSty" />
        </View>
      </View>
    )
  }

  return (
    <View className={"reservation-record-page"}>
      <PageList
        ref={pageListRef}
        params={params}
        request={trainingInfoList}
        renderItem={renderListItem}
        renderHeader={renderHeader}
      />


      {/* <Popup
        round
        visible={recoverVisible}
        className="modal-refuse"
        position="bottom"
        onClose={() => {
          setRecoverVisible(false);
        }}
      >
        <View className="modal-refuse-header">
          <Text>强制收回</Text>
        </View>
        
        <View className="modal-refuse-bottom">
          <Button block type="info" onClick={()=>setRecoverVisible(false)}>
            提交
          </Button>
        </View>
      </Popup> */}

      {/* <View className={"list-wrapper"}>
        <InfiniteLoading
          empty={empty}
          onLoad={onLoad}
          onRefresh={onPull}
          refreshing={refreshing}
        >
          {listData?.map((item) => (
            <View
              className={"list-item"}
              onClick={(e) => toDetail(e, item)}
            >
              <View className="tie">
                <View className="iteWrap" style={{ flex: 1 }}>
                  <Text className="ites">
                    {item.trainingTime?.substr(0, 16)}
                  </Text>
                  <Text className="reTypeText" style={{ color: matchType(item?.auditState).color, backgroundColor: matchType(item?.auditState).bgColor }}>
                    {matchType(item?.auditState).name}
                  </Text>

                </View>
                <Text className="rightDes">
                  {item.startTime}
                </Text>
                <Image className="rightIcon" src={iconRightGray} />
              </View>
              <View className="content">
                <Text className="companyName">{item.enterpriseName}</Text>
                <View>
                  <Text className="pNum">培训人数：{item.number}</Text>
                  <Text className="pNum" style={{ marginLeft: 12 }}>辖区：{getSystemDictValue(13, item?.jurisdiction)?.name}</Text>
                  <Text className="pNum" style={{ marginLeft: 12 }}>单位类别：{getSystemDictValue(77, item?.category)?.name}</Text>
                </View>
              </View>
              <View className="btnWrap" style={{ justifyContent: item.auditState === 3 ? "flex-start" : "flex-end" }}>
                {
                  item.auditState === 3 &&
                  <Text>拒绝原因：{item.auditReason}</Text>
                }
                {
                  item.auditState === 2 &&
                  <>
                    <Button size="large" type="success" style={{ marginRight: '12px' }} onClick={(e) => setVisibleFn(e, item)}> 编 辑 </Button>
                    <Button onClick={(e) => endPeixun(e, item)} size="large" type="info" style={{}}>完成培训</Button>
                  </>
                }
                {
                  item.auditState === 1 && <Button onClick={(e) => toDetail(e, item)} size="large" type="info" style={{}}>处 理</Button>
                }
              </View>

            </View>
          ))}
          {listData?.length > 0 && <InfiniteLoadingFoot state={loadMore} />}
        </InfiniteLoading>
      </View> */}

      {/* <Button className="AddBtn" block size="large" type="info" style={{}} onClick={() => {
        navigateTo("/pages/apply/index")
      }}>新增培训申请</Button> */}



      <DatePicker
        title="选择日期"
        visible={timeStartVisible}
        defaultValue={new Date(params.startDate)}
        showChinese
        onClose={() => {
          setTimeStartVisible(false);
        }}
        onConfirm={(options, values) => confirmTime(values, options)}
      />

      <DatePicker
        title="结束日期"
        visible={timeEndVisible}
        defaultValue={new Date(params.endDate)}
        showChinese
        onClose={() => { setTimeEndVisible(false) }}
        onConfirm={(options, values) => confirmTime(values, options)}
      />

      <Dialog
        className="test-dialog"
        title="完成培训"
        visible={endVisible}
        onConfirm={() => setEndVisible(false)}
        onCancel={() => setEndVisible(false)}
        footer={
          <View className="dialogBtnWrap">
            <Button size="large" block type="default" color="#E8F2FF" style={{ color: '#415FFF' }} onClick={() => {
              setEndVisible(false)
            }}>
              取消
            </Button>
            <Button onClick={() => {
              overSubmit()
            }} block size="large" type="info" style={{}}>
              确定
            </Button>
          </View>
        }
      >

        <View className="overWrap">
          {/* <View className="overTitWrap"><Text>完成培训</Text></View> */}
          <Text className="imgTitle">培训图片</Text>
          <View className="sImgWrap">

            {
              imgList.map((v, i) => {
                return (
                  <View className="uploadItem">
                    <Image src={baseUrl + v} className="sImg" />
                    <View className="iconCloseSty" onClick={() => delImg(i)}>
                      {/* <Text className="chacha">✖</Text> */}
                      <Text className="chacha">删除</Text>
                    </View>
                  </View>
                )
              })
            }
            <View className="uploadDefault" onClick={selectImg}>
              <Image src={iconAdd} className="iconAdd" />
              <Text className="upText">上传图片</Text>
            </View>
          </View>
          <Text className="imgTip">最多可上传10张图片</Text>
          {/* <View className="dialogBtnWrap">
            <Button size="large" block type="default" color="#E8F2FF" style={{ color: '#415FFF' }} onClick={() => {
              setEndVisible(false)
            }}>
              取消
            </Button>
            <Button onClick={() => {
              overSubmit()
            }} block size="large" type="info" style={{}}>
              确定
            </Button>
          </View> */}
        </View>
      </Dialog>

      <Picker
        title="选择培训时间"
        visible={isVisible2}
        options={timeList}
        onClose={() => setIsVisible2(false)}
        onChange={changePicker}
        onConfirm={(options, values) => {
          setTrainingTime(values[0] + ' ' + values[1])
        }}
      />

      <Picker
        title="状态筛选"
        visible={visible}
        options={listData1}
        onConfirm={(list, values) => confirmPicker(list, values)}
        onClose={() => setVisible(false)}
        onChange={changePicker}
      />

      {/* <EditModal
        visible={editVisible}
        close={() => { setEditVisible(false) }}
        submit={(name,id) => {
          console.log(name);
          editList(name,id)
        }}
      /> */}

      <EditModal
        auditType={2}
        trainingTime={trainingTime}
        visible={editVisible}
        close={() => { setEditVisible(false) }}
        onChangeTime={(time) => {
          setTrainingTime(time)
        }}
        submit={(leturerName, leturer) => {
          editList(leturerName, leturer)
        }}
      />
    </View>
  );
}
